package com.xuebusi.toutiao.admin.api.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuebusi.toutiao.admin.api.common.config.GlobalConfig;
import com.xuebusi.toutiao.admin.api.common.result.PageInfo;
import com.xuebusi.toutiao.admin.api.user.dao.SourceDao;
import com.xuebusi.toutiao.admin.api.user.entity.SourceEntity;
import com.xuebusi.toutiao.admin.api.user.service.SourceService;
import com.xuebusi.toutiao.admin.api.user.vo.SourceJoinVO;
import com.xuebusi.toutiao.admin.api.user.vo.SourceQueryPVO;
import com.xuebusi.toutiao.admin.api.user.vo.SourceRVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("sourceService")
public class SourceServiceImpl extends ServiceImpl<SourceDao, SourceEntity> implements SourceService {
    @Resource
    private GlobalConfig globalConfig;

    @Resource
    private SourceDao sourceDao;

    /**
     * 分页查询用户图片素材
     *
     * @param userId         用户id
     * @param sourceQueryPVO 查询条件
     * @return
     */
    @Override
    public ResponseEntity<PageInfo<SourceRVO>> getImages(Integer userId, SourceQueryPVO sourceQueryPVO) {
        Boolean collect = sourceQueryPVO.getCollect();
        Long page = sourceQueryPVO.getPage();
        Long perPage = sourceQueryPVO.getPer_page();
        Long pageIndex = (page - 1) * perPage;
        int totalCount = sourceDao.getImagesCount(userId, collect);
        List<SourceJoinVO> images = sourceDao.getImages(userId, collect, pageIndex, perPage);
        List<SourceRVO> results = new ArrayList<>();
        for (SourceJoinVO image : images) {
            SourceRVO sourceRVO = new SourceRVO();
            sourceRVO.setId(image.getId());
            sourceRVO.setUrl(globalConfig.getWebSite() + image.getUrl());
            sourceRVO.setIs_collected(image.getCollectId() != null);
            results.add(sourceRVO);
        }
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal_count(Long.valueOf(totalCount));
        pageInfo.setPage(page);
        pageInfo.setPer_page(perPage);
        pageInfo.setResults(results);
        return ResponseEntity.ok(pageInfo);
    }
}
